import json

from flask import jsonify, make_response, request, g, send_file
from flask_restful import Resource


from apps.model.serializeModel import model_to_list, model_to_dict
from apps.settingApi.switchCase.casePrimaryKey import caseGetPrimaryKeyData
from apps.settingApi.switchCase.serializeParameter import serializeGetFilter, pageResultData, getArgsData, \
    serializeParData

from apps.settingApi.switchCase.settingCurd import getPk, deletePk, putPk, postList
from apps.settingApi.api.file.model import fileModel
from comm.const import FILEPATH
from comm.sqlalchemyConfig import db
from comm.decorator import login_required


fileViewModel = fileModel

class fileListView(Resource):
    # 查询列表
    @login_required()
    def get(self):
        # 获取所有的参数
        serializeFilterList, args = serializeGetFilter(fileViewModel)
        print(serializeFilterList)
        serializeFilterList.append(fileViewModel.lessees_id==g.lessees_id)
        modelDataObj = fileViewModel.query.filter(*serializeFilterList).order_by(
            fileViewModel.id.asc()).paginate(page=args['page'], per_page=args['pageSize'], error_out=False)
        objData = pageResultData(modelDataObj)
        result = model_to_list(modelDataObj, [])
        objData["data"] = result  # 分页数据
        return make_response(jsonify({'msg': '成功', 'result': objData}), 200)

    @login_required()
    def post(self):
        # 获取所有参数
        args, err = getArgsData()
        if err !=None:
            return make_response(jsonify({'msg': '参数获取失败'}), 202)
        args['lessees_id'] = g.lessees_id
        objData, err = postList(fileViewModel, args)
        if err != None:
            return make_response(jsonify({'msg': err}), 202)
        return make_response(jsonify({'msg': '成功', 'result': objData}), 200)

class filePkView(Resource):
    @login_required()
    def get(self, pk):
        objData, err = getPk(fileViewModel, pk)
        if err != None:
            return make_response(jsonify({'msg': err}), 202)
        return make_response(jsonify({'msg': '成功', 'result': objData}), 200)

    @login_required()
    def put(self, pk):
        # 获取所有参数
        args, err = getArgsData()
        print(args)
        print(pk)
        if err != None:
            return make_response(jsonify({'msg': err, }), 202)
        # 序列化跟校验参数
        addData, err = serializeParData(model=fileViewModel, argsData=args)
        if err != None:
            return make_response(jsonify({'msg': err}), 202)
        objData, err = putPk(fileViewModel, pk, addData)
        if err != None:
            return make_response(jsonify({'msg': err}), 202)
        return make_response(jsonify({'msg': '成功', 'result': objData}), 200)

    @login_required()
    def delete(self, pk):
        # 查询数据
        result = fileViewModel.query.filter(fileViewModel.id == pk,fileViewModel.lessees_id==g.lessees_id).first()
        if result == None:
            return make_response(jsonify({'msg': '数据不存在'}), 202)
        resultData = model_to_dict(result, [])
        try:
            deletedata = db.session.query(fileViewModel).filter(fileViewModel.id == pk).first()
            db.session.delete(deletedata)
            db.session.commit()
        except Exception as e:
            return make_response(jsonify({'msg': '数据删除失败' + repr(e)}), 202)
        return make_response(jsonify({'msg': '成功', 'result': resultData}), 200)

class uploadListView(Resource):
    @login_required()
    def get(self):
        args = request.args
        id_z = args.get('id',None)
        # 查询文件的地址
        if id_z == "" or id_z == None:
            return make_response(jsonify({'msg': '参数不能为空'}), 202)
        import os
        # 查询文件的地址
        data = db.session.query(fileViewModel).filter(fileViewModel.id == id_z).first()
        # 文件路径
        file_path = os.path.abspath(os.curdir) + '\\' +FILEPATH + '\\' + data.url
        return send_file(file_path)
    @login_required()
    def post(self):
        import os
        # 要检查的目录路径
        directory_path = FILEPATH
        # 检查目录是否存在
        if not os.path.exists(directory_path):
            # 如果目录不存在，则创建它
            os.makedirs(directory_path)
        uploadFiled = request.files.get("uploadFiled", None)

        # 格式化到毫秒级（取前三位的微秒）
        date_time_ms = caseGetPrimaryKeyData()
        if str(uploadFiled.filename.split('.')[1]) not in ['png']:
            return make_response(jsonify({'msg': '文件格式不对'}), 202)
        try:
            url = date_time_ms + '.' + str(uploadFiled.filename.split('.')[1])
            uploadFiled.save(FILEPATH + '/' + url)
        except Exception as e:
            return make_response(jsonify({'msg': '上传失败' + repr(e)}), 202)

        print(os.path.abspath(os.curdir))

        return make_response(jsonify({'msg': '上传成功', "result": {"url":url, "postfix":str(uploadFiled.filename.split('.')[1])}}), 200)